//: Sample based on Function Composition snippet from objc.io: http://www.objc.io/snippets/2.html

import Foundation

func getContents(url: String) -> String {
    return NSString(contentsOfURL: NSURL(string: url)!, encoding: NSUTF8StringEncoding, error: nil)! as String
}
func lines(input: String) -> [String] {
    return input.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
}

// WITHOUT COMPOSITION ---------------------------------------------------------------------------------------

let linesInURL = { url in count(lines(getContents(url))) }("http://www.objc.io/books")

// CASE A (process from right to left) -----------------------------------------------------------------------

infix operator <<< { associativity left }
func <<< <A, B> (f: A -> B, x: A) -> B {
    return f(x)
}
func <<< <A, B, C> (f: B -> C, g: A -> B) -> (A -> C) {
    return { x in f(g(x)) }
}

let linesInURL2 = (count <<< lines <<< getContents)("http://www.objc.io/books")
let linesInURL3 = count <<< lines <<< getContents <<< "http://www.objc.io/books"

// CASE B (process from left to right) -----------------------------------------------------------------------

infix operator >>> { associativity left }
func >>> <A, B> (s: A, f: A -> B) -> B {
    return f(s)
}
func >>> <A, B, C> (f: A -> B, g: B -> C) -> (A -> C) {
    return { x in g(f(x)) }
}

let linesInURL4 = "http://www.objc.io/books" >>> getContents >>> lines >>> count

